package com.seed.application.context.impl;

import com.seed.application.Sa;
import com.seed.application.context.Custom;
import com.seed.application.context.SeedContext;
import com.seed.core.action.Action;
import com.seed.core.pojo.seed.Seed;
import com.seed.core.query.App;
import com.seed.core.query.Micro;
import com.seed.manager.LibManager;
import com.seed.uaa.Uaa;
import com.seed.uaa.util.MergeUtil;
import com.seed.util.ActionsKit;
import com.seed.util.AppLoadKit;

import java.util.List;
import java.util.Map;

public class MicroSeedContext implements SeedContext {

    private final App app;

    public MicroSeedContext() {
        this.app = new App(Sa.getConfiguration());

        init();
    }

    public void init() {
        List<String> libNames = app.getConfigurationLibs();
        Map<String, Seed> libSeeds = LibManager.getLibSeeds(libNames);
        libSeeds.putAll(Uaa.getSeeds());
        Map<String, Seed> seeds = MergeUtil.initSeeds(
                app.getConfigurationSeeds(),
                libSeeds,
                Custom.getSeeds()
        );

        Map<String, Action> libActions = LibManager.getLibActions(libNames);
        libActions.putAll(Uaa.getActions());
        Map<String, Action> actions = MergeUtil.initActions(
                ActionsKit.initMethods(app.getConfigurationActions()),
                libActions,
                Custom.getActions()
        );

        app.setSeeds(seeds);
        app.setActions(actions);
        Sa.getDdl().run(seeds); // 使用主库，即springboot配置文件里配置的数据库

        // TODO 初始化租户库
//        List<String> tenantnames = DataSourceKey.use(
//                dataSourceKey,
//                () -> QueryChain.of(Tenant.class).select(TENANT.TENANTNAME).objListAs(String.class)
//        );
//        // 创建租户库
//        for(String tenantname: tenantnames) {
//            String tenantDataSourceKey = StrKit.dataSourceKey(owner, appName, tenantname, microName);
//            DDLManager.run(tenantDataSourceKey, datasource, seeds);
//        }
    }

    @Override
    public App getApp() {
        return app;
    }

    @Override
    public Micro getMicro() {
        return app.getMicro(null);
    }
}
